package com.example.handler;

import com.alibaba.fastjson.JSON;
import com.example.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/2/4 20:47
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private Properties properties;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        /*if (msg.toString().startsWith("UserService")) {
            UserServiceImpl userService = new UserServiceImpl();
            System.out.println(msg.toString());
            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush("success");
        }*/
        // System.out.println(msg.toString());
        // String message = msg.toString().substring(msg.toString().indexOf("{"));
        // RpcRequest request = JSON.parseObject(message, RpcRequest.class);
        RpcRequest request = (RpcRequest) msg;
        Object result = handler(request);
        ctx.writeAndFlush("success");
    }

    private Object handler(RpcRequest request) throws Exception {
        if (properties == null) {
            loadProperties();
        }
        String className = request.getClassName();
        String impl = properties.getProperty(className);
        String methodName = request.getMethodName();
        Class<?>[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();

        Class<?> aClass = Class.forName(impl);
        Method method = aClass.getDeclaredMethod(methodName, parameterTypes);

        return method.invoke(aClass.newInstance(), parameters);
    }

    private void loadProperties() throws IOException {
        Properties properties = new Properties();
        properties.load(this.getClass().getClassLoader().getResourceAsStream("serviceImpl.properties"));
        this.properties = properties;
    }


}
